<template>
    <div class="login">
        <p class="login_title pc-box">{{ type === 'login' ? $t('login.login') : $t('login.register') }}</p>
        <div class="login_form">
            <p class="login_form_title pc-box">{{$t('login.welcomeBack')}}</p>
            <a-form
                ref="formRef"
                :model="formData"
                :rules="formRules"
                layout="vertical"
            >
                <div class="login_form_inner">
                    <a-form-item class="l-f1" :label="$t('header.account')" name="username">
                        <a-input class="login_form_input" v-model:value="formData.username" :placeholder="$t('login.emailPlaceholder')" aria-autocomplete="off" />
                    </a-form-item>
                    <a-form-item class="l-f1" :label="$t('login.password')" name="password">
                        <a-input class="login_form_input" v-model:value="formData.password" :placeholder="$t('login.enterYourPassword')" aria-autocomplete="off"  />
                    </a-form-item>
                    <template v-if="type === 'register'">
                         <a-form-item class="l-f1" :label="$t('login.confirmPassword')" name="confirmPassword">
                            <a-input class="login_form_input" v-model:value="formData.confirmPassword" :placeholder="$t('login.confirmPasswordPlaceholder')" aria-autocomplete="off"  />
                        </a-form-item>
                        <a-form-item class="l-f1" :label="$t('login.emailCode')" name="emailCode">
                            <div class="login_form_code">
                                <a-input class="login_form_input l-f1" v-model:value="formData.emailCode" :placeholder="$t('login.emailCodePlaceholder')" aria-autocomplete="off"  />
                                <a-button  @click.stop="onSend" type="primary" :disabled="isSend ? true : false" class="login_form_code_btn" 
                                :class="isSend ? 'disabled' : ''">{{isSend ? timeVal + 's' : $t('login.send')}}</a-button>
                            </div>
                        </a-form-item>
                        <a-form-item class="l-f1" :label="$t('account.withdrawalPassword')" name="payPassword">
                            <a-input class="login_form_input" v-model:value="formData.payPassword" :placeholder="$t('account.withdrawalPasswordPlaceholder')" aria-autocomplete="off"  />
                        </a-form-item>
                    </template>
                </div>
                <a-form-item>
                    <a-button class="login_form_submit" type="primary" @click="onSubmit">{{ type === 'login' ? $t('login.login') : $t('login.register') }}</a-button>
                </a-form-item>
            </a-form>
            <div class="login_form_bottom l-f l-row-c">
                <p class="login_form_bottom_desc">{{type === 'login' ? $t('login.donTHaveAnAccount') : $t('login.haveAnAccount')}}</p>
                <router-link class="login_form_bottom_btn" :to="type === 'login' ? '/register' : '/login'" >{{type === 'login' ? $t('login.registerNow') : $t('login.login')}}</router-link>
            </div>
        </div>
    </div>
</template>

<script setup>
    import { ref, reactive } from 'vue'
    import { useI18n } from 'vue-i18n'
    import { useMainStore } from '@/store'
    import { useRouter } from 'vue-router'
    import { message } from 'ant-design-vue'
    import { throttle } from '@/utils/index.js'

    import {
        postRegisterApi,
        postLoginApi,
        postSendCodeApi
    } from '@/api/userApi'

    const props = defineProps({
        type: String,
        default: 'login'
    })

    const { t } = useI18n()
    const mainStore = useMainStore()
    const router = useRouter()

    const formRef = ref(null)
    const formData = reactive({
        username: '',
        password: '',
        confirmPassword: '',
        emailCode: '',
        payPassword: ''
    })
    const formRules = {
         username: [
            { required: true, message: t('login.emailPlaceholder'), trigger: 'change' }
        ],
         password: [
            { required: true, message: t('login.enterYourPassword'), trigger: 'change' }
        ],
        confirmPassword: [
            { required: true, message: t('login.confirmPasswordPlaceholder'), trigger: 'change' }
        ],
        emailCode: [
            { required: true, message: t('login.emailCodePlaceholder'), trigger: 'change' }
        ],
        payPassword: [
            { required: true, message: t('account.withdrawalPasswordPlaceholder'), trigger: 'change' }
        ],
    }
    const isSend = ref(false)
    const timeId = ref(null)
    const timeVal = ref(60)

    const onSubmit = throttle(() => {
        formRef.value
            .validate()
            .then(async () => {
                let token = ''
                // 登录
                if(props.type === 'login') {
                    const loginRes = await postLoginApi({
                        type: 1,
                        user_string: formData.username,
                        password: formData.password,
                    })
                    message.success(t('login.welcomeBack'))
                    token = loginRes
                }else {
                    const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
                    if(!regex.test(formData.username)) {
                        message.error(t('home.emailEnteredIsInvalid'))
                        return
                    }
                    if(formData.password !== formData.confirmPassword) {
                        message.error(t('login.twoPasswordsAreInconsistent'))
                        return
                    }
                    const registerRes = await postRegisterApi({
                        type: 1,
                        user_string: formData.username,
                        password: formData.password,
                        re_password: formData.confirmPassword,
                        pay_password: formData.payPassword,
                        code: formData.emailCode
                    })
                    message.success(registerRes.msg)
                    token = registerRes.token
                }
                mainStore.setToken(token)
                mainStore.getUserBalance()
                mainStore.getUserInfoApi()
                setTimeout(() => {
                    router.replace('/home')
                },800)
            })
            .catch(error => {
            console.log('error', error);
            });
        },3000);

        const onSend = throttle(async () => {
            if(!formData.username) {
                message.error(t('login.emailPlaceholder'))
                return
            }
             const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
            if(!regex.test(formData.username)) {
                 message.error(t('home.emailEnteredIsInvalid'))
                 return
            }
            isSend.value = true
            const res = await postSendCodeApi({
                user_string: formData.username,
                scene: 'register'
            })
           message.success(res)
            timeId.value = setInterval(() => {
                timeVal.value --
                if(timeVal.value <=0) {
                    timeVal.value = 60
                    clearInterval(timeId)
                    isSend.value = false
                }
            },1000)
        },3000)
</script>

<style lang="scss" scoped>
.login{
    &_title {
        padding-top: 40px;
        padding-bottom: 20px;
        box-sizing: border-box;
        font-size: 30px;
        text-align: center;
        font-weight: 600;
    }
    &_form {
        border-radius: 24.15px;
        background: #171d33b3;
        padding: 36px;
        max-width: 600px;
        margin: auto;
        margin-top: 16px;
        &_title {
            font-size: 16px;
            color: #ffffff;
            font-weight: 400;
            text-align: center;
            line-height: 40px;
            margin-top: 20px;
            margin-bottom: 20px;
        }
        &_inner {
            gap: 10px;
        }
        &_input {
            width: 100%;
            height: 56px;
            background: #d9d9d90d;
            border-radius: 8px;
            border: none;
            padding: 0 16px;
            color: #fff;
        }
        &_submit {
            width: 100%;
            height: 52px;
            font-weight: 700;
        }
        &_bottom {
            &_desc {
                font-size: 14px;
                color: #ffffff;
            }
            &_btn {
                font-size: 14px;
                color: #ffffff;
                font-weight: 700;
                margin-left: 4px;
            }
        }
        &_code {
            position: relative;
            &_btn {
                position: absolute;
                right: 15px;
                top: 50%;
                transform: translateY(-50%);
            }
        }
    }
}
.disabled {
    background: transparent !important;
    color: #ffffff !important;
    border-color: transparent;
}
:deep(.ant-form-item .ant-form-item-label >label)  {
    color: #ffffff;
    font-size: 16px;
    font-weight: 400;
    opacity: .6;
}
:deep(.ant-form-item .ant-form-item-label >label.ant-form-item-required:not(.ant-form-item-required-mark-optional)::before) {
    display: none;
}
input::-webkit-input-placeholder {  
    color: #ffffff;
    opacity: .3;  
    font-size: 16px;
}


@media only screen and (max-width: 1200px) {
    .pc-box {
        display: none;
    }
    .login {
        &_form {
            background-color: transparent;
            padding-left: 0;
            padding-right: 0;
             max-width: 100%;
            &_inner {
                display: block;
            }
        }
    }
}
</style>